package com.fs.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.fs.entity.Product;
import com.fs.entity.ShopCart;
import com.fs.utils.DBUtils;

public class ShopCartDao {
	//点击加入购物车，将数据保存到数据库
	public int add(ShopCart shopcart) {
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		int product_id = 0;
		String sql="insert into tb_shopcart(user_id,product_pic,product_name,product_price) values(?,?,?,?)";
		try {
			 con= DBUtils.getConnection();//获取数据库连接
			 ps=con.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);//执行预编译的sql语句
			 ps.setInt(1,shopcart.getUser_id());
			 ps.setString(2, shopcart.getProduct_pic());
			 ps.setString(3, shopcart.getProduct_name());
			 ps.setString(4,shopcart.getProduct_price());
			 ps.execute();
			 rs= ps.getGeneratedKeys();  
			    while(rs.next()){
			    	product_id = rs.getInt(1);
			   }
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			DBUtils.close(con, rs, null, ps);
		}
		return product_id;
	}
	
	
	
	//商品加入购物车之后，根据user_id  获取到所有的商品列表
	public List<ShopCart> queryAllProduct(int user_id){
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		String sql="select * from tb_shopcart where user_id=?";
		List<ShopCart> list=new ArrayList<ShopCart>();
		
		try {
			con=DBUtils.getConnection();
			ps=con.prepareStatement(sql);
			ps.setInt(1, user_id);
			rs=ps.executeQuery();
			ShopCart shopcart = null;
			while (rs.next()) {
				shopcart = new ShopCart();
				shopcart.setUser_id(rs.getInt("user_id"));
				shopcart.setProduct_id(rs.getInt("product_id"));
				System.out.println(rs.getInt("product_id")+"ssss");
				shopcart.setProduct_pic(rs.getString("product_pic"));
				shopcart.setProduct_name(rs.getString("product_name"));
				shopcart.setProduct_price(rs.getString("product_price"));
				list.add(shopcart);
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			DBUtils.close(con, rs, null, ps);
		}
		return list;
	}

}
